package com.caiguoping.javayuv;

public class Test2 {

    public static void NV21ToABGR(int width, int height, byte[] nv21, byte[] abgr) {
        int nvOff = width * height;
        int i, j, yIndex = 0;
        int y, u, v;
        int r, g, b, nvIndex;
        for (i = 0; i < height; i++) {
            for (j = 0; j < width; j++, ++yIndex) {
                nvIndex = (i / 2) * width + j - j % 2;
                y = nv21[yIndex] & 0xff;
                u = nv21[nvOff + nvIndex] & 0xff;
                v = nv21[nvOff + nvIndex + 1] & 0xff;

                r = y + ((360 * (v - 128)) >> 8);
                g = y - (((88 * (u - 128) + 184 * (v - 128))) >> 8);
                b = y + ((455 * (u - 128)) >> 8);

                r = r > 255 ? 255 : (Math.max(r, 0));
                g = g > 255 ? 255 : (Math.max(g, 0));
                b = b > 255 ? 255 : (Math.max(b, 0));

                abgr[yIndex * 4] = (byte) b;
                abgr[yIndex * 4 + 1] = (byte) g;
                abgr[yIndex * 4 + 2] = (byte) r;
                abgr[yIndex * 4 + 3] = (byte) 0;
            }
        }
    }

    public static void ABGRToNV21(int width, int height, byte[] abgr, byte[] nv21) {
        int nvOff = width * height;
        int i, j, yIndex = 0;
        int y, u, v;
        int r, g, b, nvIndex;
        for (i = 0; i < height; i++) {
            for (j = 0; j < width; j++, ++yIndex) {
                nvIndex = (i / 2) * width + j - j % 2;

                r = abgr[yIndex * 4] & 0xff;
                g = abgr[yIndex * 4 + 1] & 0xff;
                b = abgr[yIndex * 4 + 2] & 0xff;

                y = (77 * r + 150 * g + 29 * b) >> 8;
                u = ((-44 * r - 87 * g + 131 * b) >> 8) + 128;
                v = ((131 * r - 110 * g - 21 * b) >> 8) + 128;

                nv21[yIndex] = (byte) y;
                nv21[nvOff + nvIndex] = (byte) v;
                nv21[nvOff + nvIndex + 1] = (byte) u;
            }
        }
    }

}